package com.zhongshengnetwork.rightbe.commentstore.view;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.wang.avi.AVLoadingIndicatorView;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.commentstore.activity.CommentHomeActivity;
import com.zhongshengnetwork.rightbe.commentstore.activity.CommentStoreActivity;
import com.zhongshengnetwork.rightbe.commentstore.activity.CommentStoreClassifyActivity;
import com.zhongshengnetwork.rightbe.commentstore.activity.NewCommentStoreActivity;
import com.zhongshengnetwork.rightbe.commentstore.activity.NewCommentStoreClassifyActivity;
import com.zhongshengnetwork.rightbe.commentstore.model.CommentStoreClassifyModel;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.BaseAnalyticsFragment;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.huantansheng.easyphotos.constant.Code.REQUEST_PERMISSION;

public class CommentStoreClassifyFragment extends BaseAnalyticsFragment {

    private View rootView;//缓存Fragment view

    private String dataContent = "";

    private int pageindex = 0;
    private static final int Records = 20;
    private boolean isGetting = false;
    private boolean isHasMore = false;
    private List<CommentStoreClassifyModel> list;
    private ListView listview;
    private MyAdapter adapter;

    //加载动画
    private AVLoadingIndicatorView avi;
    private RefreshLayout mRefreshLayout;

    private EditText search_edit;
    private Button search_button;
    private ImageView no_data_img;
    private Button publish_button;
    private CommentStoreClassifyModel classifyModel = null;

    public CommentHomeActivity commentHomeActivity = null;
    public String sourceId = null;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){

        if (rootView == null){
            rootView = inflater.inflate(R.layout.comment_store_classify_fragment, container, false);
            pageindex = 0;
            if (list == null){
                list = new ArrayList<CommentStoreClassifyModel>();
            }
            listview=(ListView) rootView.findViewById(R.id.classify_listview);
            adapter=new MyAdapter();
            listview.setAdapter(adapter);

            listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    hintKeyBoard();
                    if (list != null && list.size() > 0){
                        if (i >= list.size()){
                            i-=1;
                        }
                        CommentStoreClassifyModel model = list.get(i);
                        Intent intent = new Intent(getActivity(), CommentStoreActivity.class);
                        Bundle bundle=new Bundle();
                        bundle.putSerializable("model", model);//序列化
                        if (!CommonUtils.isEmpty(sourceId)){
                            intent.putExtra("sourceId", sourceId);
                        }
                        intent.putExtras(bundle);//发送数据
                        startActivity(intent);
                    }
                }
            });

            listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                    hintKeyBoard();
                    if (list != null && list.size() > 0){
                        if (i >= list.size()){
                            i -= 1;
                        }
                        classifyModel = list.get(i);
                        final List<String> menu = new ArrayList<>();
                        menu.add("编辑");
                        menu.add("删除");
                        ActionSheetDialog actionSheetDialog = new ActionSheetDialog(getActivity())
                                .builder()
                                .setTitle("请选择")
                                .setCancelable(false)
                                .setCanceledOnTouchOutside(true);
                        for (String s : menu){
                            actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                                @Override
                                public void onClick(int which) {
                                    if (which > 0){
                                        which -= 1;
                                        String title = menu.get(which);
                                        if (title.equals("编辑")){
                                            if (classifyModel != null){
//                                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
//                                                        && ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//                                                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
//                                                            REQUEST_PERMISSION);
//                                                    ToastUtil.show(getActivity(),"亲，请开启应用对SD卡的读写权限");
//                                                    return;
//                                                }
                                                commentHomeActivity.addCommentStore();
                                            }
                                        }else if (title.equals("删除")){
                                            CustomDialog dialog = null;
                                            final CustomDialog.Builder builder = new CustomDialog.Builder(getActivity());
                                            builder.setTitle("温馨提示");
                                            builder.setMessage("是否要删除评论库："+classifyModel.getClassifyName()+"？");
                                            builder.setPositiveButton("删除", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    dialog.dismiss();
                                                    deleteClassify();
                                                }
                                            });
                                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    dialog.dismiss();
                                                }
                                            });
                                            dialog = builder.create();
                                            dialog.show();
                                        }
                                    }
                                }
                            });
                        }
                        actionSheetDialog.show();
                    }
                    return true;
                }
            });

            no_data_img = (ImageView) rootView.findViewById(R.id.no_data_img);
            publish_button = (Button) rootView.findViewById(R.id.publish_button);
            publish_button.setBackgroundResource(AppThemeUtils.getInstance().getButtonBg());
            publish_button.setClickable(true);
            publish_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
//                            && ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//                        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
//                                REQUEST_PERMISSION);
//                        ToastUtil.show(getActivity(),"亲，请开启应用对SD卡的读写权限");
//                        return;
//                    }
                    commentHomeActivity.addCommentStore();
                }
            });
            mRefreshLayout = (RefreshLayout) rootView.findViewById(R.id.refreshLayout);
            //设置 Header 为 贝塞尔雷达 样式
            mRefreshLayout.setRefreshHeader(new BezierRadarHeader(getActivity()).setEnableHorizontalDrag(true));//BezierRadarHeader
            //设置 Footer 为 球脉冲 样式
            mRefreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()).setSpinnerStyle(SpinnerStyle.FixedBehind));//BallPulseFooter ClassicsFooter
            mRefreshLayout.setPrimaryColors(AppThemeUtils.getInstance().getRefreshBackgroundColor(),AppThemeUtils.getInstance().getRefreshAccessColor());
            mRefreshLayout.setEnableRefresh(true);//启用刷新
            mRefreshLayout.setEnableLoadMore(true);//启用加载
            //刷新
            mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(RefreshLayout refreshlayout) {
                    //refreshlayout.finishRefresh();
                    pageindex = 0;
                    getData();
                }
            });
            mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
                @Override
                public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                    //refreshLayout.finishLoadMore();
                    getData();
                }
            });

            search_edit = (EditText) rootView.findViewById(R.id.search_edit);
            search_button = (Button) rootView.findViewById(R.id.search_button);
            search_button.setTextColor(Color.WHITE);
            search_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onClickSearch(v);
                }
            });

            RelativeLayout classify_layout = (RelativeLayout) rootView.findViewById(R.id.classify_layout);
            classify_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            listview.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
            listview.setDivider(new ColorDrawable(AppThemeUtils.getInstance().getBackgroundColor()));
            listview.setDividerHeight(ScreenUtils.dip2px(getActivity(), 1));

            search_edit.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());
            search_edit.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
            RelativeLayout search_top = (RelativeLayout) rootView.findViewById(R.id.search_top);
            search_top.setBackgroundColor(AppThemeUtils.getInstance().getSearchBgColor());
            RelativeLayout search_shape_layout = (RelativeLayout) rootView.findViewById(R.id.search_shape_layout);
            search_shape_layout.setBackgroundResource(AppThemeUtils.getInstance().getSearchBackground());

            mRefreshLayout.autoRefresh();
        }else {
            //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        }

        return rootView;
    }

    //删除收藏夹
    private void deleteClassify(){
        if (classifyModel != null){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    final HashMap<String, String> map = new HashMap<String, String>();
                    String url = "comment/store/delete.do";
                    map.put(APIKey.tokenKey, CommonUtils.formatString(CustomApplication.loginModel.getToken()));
                    map.put("classifyId", "" + classifyModel.getClassifyId());
                    HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                        @Override
                        public void onSuccess(String data) {
                            CommonModel commonModel = GsonTools.getCommonModel(data);
                            if (getActivity() == null){
                                return;
                            }
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (commonModel.getFlag().equals("1")){
                                        ToastUtil.show(getActivity(), "删除成功");
                                        list.remove(classifyModel);
                                        adapter.notifyDataSetChanged();
                                    }else {
                                        CustomApplication.showTip(commonModel, getActivity());
                                    }
                                }
                            });
                        }

                        @Override
                        public void onError(String msg) {

                        }
                    });
                }
            }){

            }.start();
        }
    }

    public void hintKeyBoard() {
        //拿到InputMethodManager
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        //如果window上view获取焦点 && view不为空
        if (imm.isActive() && getActivity().getCurrentFocus() != null) {
            //拿到view的token 不为空
            if (getActivity().getCurrentFocus().getWindowToken() != null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    private void onClickSearch(View view){
        hintKeyBoard();
        String text = search_edit.getText().toString();
        dataContent = text;
        if (mRefreshLayout != null){
            Log.e("TAG","进来获取数据了刷新界面");
                /*
                @param delayed 开始延时
                @param duration 拖拽动画持续时间
                @param dragRate 拉拽的高度比率（要求 ≥ 1 ）
                */
            mRefreshLayout.autoRefresh(100,300,1f,false);
        }
    }

    public void getFirstData(boolean isFirst){

        if (isFirst == true){
            if (list != null && list.size() > 0){
                listview.setSelection(0);
            }
        }else {
            if (mRefreshLayout != null){
                mRefreshLayout.autoRefresh();
            }
        }

    }

    private void getData() {
        if (listview == null) {
            return;
        }
        if (isGetting == true) {
            return;
        }
        isGetting = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                final HashMap<String, String> map = new HashMap<String, String>();
                String url = "comment/store/list.do";
                map.put("dataContent", CommonUtils.formatString(dataContent));
                if (CommonUtils.isLogin() == true){
                    map.put(APIKey.tokenKey, CommonUtils.formatString(CustomApplication.loginModel.getToken()));
                }
                map.put("pageIndex",pageindex+"");
                map.put("pageRecord",Records+"");
                HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                    @Override
                    public void onSuccess(String data) {
                        isGetting = false;
                        CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            final List<CommentStoreClassifyModel> l = GsonTools.getCommentStoreClassifyModel(data);
                            if (getActivity() == null){
                                return;
                            }
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mRefreshLayout.getState() == RefreshState.Loading){
                                        //listview.stopLoadMore();
                                        mRefreshLayout.finishLoadMore();
                                    }else {
                                        list.clear();
                                        //listview.stopRefresh(true);
                                        mRefreshLayout.finishRefresh();
                                    }
                                    if (l != null && l.size() > 0){
                                        no_data_img.setVisibility(View.INVISIBLE);
                                        publish_button.setVisibility(View.INVISIBLE);
                                        if (l.size() >= Records){
                                            //listview.setPullLoadEnable(true);
                                            mRefreshLayout.setEnableLoadMore(true);
                                        }else {
                                            //listview.setPullLoadEnable(false);
                                            mRefreshLayout.setEnableLoadMore(false);
                                        }
                                        list.addAll(l);
                                    }else {
                                        isHasMore = false;
                                        //listview.setPullLoadEnable(false);
                                        mRefreshLayout.setEnableLoadMore(false);
                                    }
                                    adapter.notifyDataSetChanged();
                                    if (pageindex == 0){
                                        //listview.smoothScrollToPosition(0);
                                        listview.setSelection(0);
                                        if (list.size() == 0){
                                            no_data_img.setVisibility(View.INVISIBLE);
                                            publish_button.setVisibility(View.VISIBLE);
                                        }
                                    }
                                    if (l != null && l.size() > 0){
                                        pageindex += 1;
                                    }
                                }
                            });
                        }else {
                            if (getActivity() == null){
                                return;
                            }
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mRefreshLayout.getState() == RefreshState.Loading){
                                        //listview.stopLoadMore();
                                        mRefreshLayout.finishLoadMore();
                                    }else {
                                        list.clear();
                                        //listview.stopRefresh(true);
                                        mRefreshLayout.finishRefresh();
                                    }
                                    //CustomApplication.showTip(commonModel, CommentStoreClassifyActivity.this);
                                }
                            });
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        isGetting = false;
                        if (getActivity() == null){
                            return;
                        }
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (mRefreshLayout.getState() == RefreshState.Loading){
                                    //listview.stopLoadMore();
                                    mRefreshLayout.finishLoadMore();
                                }else {
                                    mRefreshLayout.finishRefresh();
                                }
                            }
                        });
                    }
                });
            }
        }){

        }.start();
    }

    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }


        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public boolean isEnabled(int position) {
            // TODO Auto-generated method stub
            return super.isEnabled(position);
        }

        /**
         * @param position
         * @param convertView
         * @param parent
         * @return
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            //convertView的复用
            if (convertView == null) {
                convertView = View.inflate(getActivity(), R.layout.classify_item_layout,null);
            }
            View view=convertView;

            CommentStoreClassifyModel model = list.get(position);
            ImageView classify_icon = (ImageView) view.findViewById(R.id.classify_icon);
            TextView classify_name = (TextView) view.findViewById(R.id.classify_name);
            TextView wzt_count = (TextView) view.findViewById(R.id.wzt_count);
            TextView wzt_title_text = (TextView) view.findViewById(R.id.wzt_title_text);
            wzt_title_text.setText("评论数量");

            View icon_bg = (View) view.findViewById(R.id.icon_bg);
            ImageView private_icon = (ImageView) view.findViewById(R.id.private_icon);
            ImageView author_icon = (ImageView) view.findViewById(R.id.author_icon);
            icon_bg.setVisibility(View.INVISIBLE);
            private_icon.setVisibility(View.INVISIBLE);
            author_icon.setVisibility(View.INVISIBLE);

            RequestOptions options = new RequestOptions().error(AppThemeUtils.getInstance().getDefaultImageBg()).bitmapTransform(new RoundedCorners(5));//图片圆角
            Glide.with(getActivity()).load(model.getIcon()).apply(options).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(classify_icon);
            classify_name.setText(model.getClassifyName());

            classify_name.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
            RelativeLayout classify_item = (RelativeLayout) view.findViewById(R.id.classify_item);
            classify_item.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            LinearLayout classify_item_line = (LinearLayout) view.findViewById(R.id.classify_item_line);
            classify_item_line.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());

            wzt_count.setText(""+model.getContentCount());

            return view;
        }
    }

}
